package com.zhou.juc.test01_thread;

/**
 * @author zhouyanxiang
 * @create 2020-06-2020/6/18-8:23
 */

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 *创建线程的四种启动方式:
 * 1、继承Thread类
 * 2、implement Runable 接口
 * 3、通过ExecutorService和Callable<Class>实现有返回值的线程
 * 4、基于线程池
 */

public class T02_HowToCreateThread {

    /**
     * 第一种：继承Thread
    */
    private  static class MyThread extends Thread{

        @Override
        public void run(){
            System.out.println("The First Thread");
        }
    }


    /**
     * 第二种：实现Runnable接口
     */
    private static class MyRun implements Runnable{

        @Override
        public void run() {
            System.out.println("The Second Thread");
        }
    }

    /**
     * 第三种：通过ExecutorService和Callable<Class>实现有返回值的线程
     */
    private static class TaskWithResult implements Callable<String>{

        @Override
        public String call() throws Exception {
            return "The Third Thread ";
        }

        public void m(){
             BlockingQueue blockingQueue=new ArrayBlockingQueue<>(1);
             ThreadPoolExecutor threadPool=new ThreadPoolExecutor(10, 20, 1, TimeUnit.SECONDS, blockingQueue);
            ArrayList<Future<String>> res = new ArrayList<Future<String>>();
            res.add(threadPool.submit(new TaskWithResult()));
            for(Future<String > r: res){
                try {
                    System.out.println(r.get());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                } finally {
                    threadPool.shutdown();
                }
            }
        }
    }


    /**
     * 第四种：基于线程池
     */
    private static class TestExecutor {
      public void method(){
          BlockingQueue blockingQueue=new ArrayBlockingQueue<>(1);
          ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 20, 1, TimeUnit.MINUTES, blockingQueue);
          threadPool.execute(new Runnable() {
              @Override
              public void run() {
                      System.out.println("The Fourth Thread");
              }
          });
          threadPool.shutdown();
      }
    }





    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();

        new Thread(new MyRun()).start();

//        new Thread(()->{
////            System.out.println(" thread ");
////        }).start();
        new TaskWithResult().m();


        TestExecutor testExecutor = new TestExecutor();
        testExecutor.method();
    }
}
